﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Chemistry.Models;
using OPCAutomation;

namespace Chemistry.WorkFlow
{
    /// <summary>
    /// 氨基化 外操版本
    /// </summary>
    class Amination : FlowBaseAll
    {

        #region 字段
        private const int DEFAULT_TEMPERATURE = 22;
        private int _reactionSecond = 30;
        private bool _isgetoverstate1;
         private bool _isgetoverstate2;
        // 组态数据
       double _flowBenzeneValue; //间二甲苯流量
       double _flowAmmoniaValue;  //氨气流量
       double _flowOxygenValue;  //空气流量
       double _pressureAmmoniaValue;//氨气压力
       double _tempratureElectricValue = DEFAULT_TEMPERATURE;  // 电加热器中温度
       double _temperature1Value = DEFAULT_TEMPERATURE; //浓1处温度
       double _temperature2Value = DEFAULT_TEMPERATURE;//浓2处温度
       double _rateAmmoniaBenzeneValue;//氨气与间二甲苯比例
       double _rateGasBenzeneValue;   //空气与间二甲苯比例

       double _flow_benzene_increament;
       double _flow_benzene_decreament;
       double _flowAmmoniaIncrement;
       double _flow_ammonia_decreament;
       double _flow_oxygen_increment;
       double _flow_oxygen_decrement;
       double _pressure_ammonia_increment;
       double _pressure_ammonia_decrement;
       double _temperature1_increment;
       double _temperature1_decrement;
       double _temperature2_increment;
       double _temperature2_decrement;
       double _rate_ammoniaBenzene_crement = 0.1;
       double _rate2_gasBenzene_crement = 0.1;
        #endregion

        #region 状态开关状态
        /// <summary>
        /// 液氨进料调节阀状态
        /// </summary>
        private bool _valveInAmmoniaState;
        /// <summary>
        /// 氨汽化罐到氨缓冲罐阀门状态
        /// </summary>
        private bool _valveAmmoniaBufTankState;
        /// <summary>
        /// 空气到加热器阀门状态
        /// </summary>
        private bool _valveO2AirHeaterState;
        /// <summary>
        /// 空气加热器到电加热器阀门状态
        /// </summary>
        private bool _valveInEleHeaterState;
        /// <summary>
        /// 氨气加热器热油阀门状态
        /// </summary>
        private bool _valveOilLeftIState;
        /// <summary>
        /// 间二甲苯汽化器 热油阀 
        /// </summary>
        private bool _valveOilRightState;
        /// <summary>
        /// 间二甲苯进料调节阀
        /// </summary>
        private bool _valveBenState;
        /// <summary>
        /// 间二甲苯进料流量调节阀
        /// </summary>
        private bool _valveBenTopState;
        /// <summary>
        /// 空气加热器通往反应器阀门
        /// </summary>
        private bool _valveO2ReactorState;
        /// <summary>
        /// 热水泵进水阀
        /// </summary>
        private bool _valveInHotPumpState;
        /// <summary>
        /// 热水进入反应器阀门
        /// </summary>
        private bool _valveH2ORecState;
        /// <summary>
        /// 热油泵阀门
        /// </summary>
        private bool _valveOilPumpState;
        /// <summary>
        /// 闸阀1
        /// </summary>
        private bool _valveGate1State;
        #endregion


        #region 组态Item

        /// <summary>
        /// 液氨进料调节阀
        /// </summary>
        private OPCItem _valveInAmmoniaItem;

        /// <summary>
        ///  氨汽化罐到氨缓冲罐
        /// </summary>
        private OPCItem _valveAmmoniaBufTankItem;

        /// <summary>
        /// 空气到加热器阀门
        /// </summary>
        private OPCItem _valveO2AirHeaterItem;
        /// <summary>
        /// 空气加热器到电加热器阀门
        /// </summary>
        private OPCItem _valveInEleHeaterItem;
        /// <summary>
        /// 氨气加热器热油阀
        /// </summary>
        private OPCItem _valveOilLeftItem;

        /// <summary>
        /// 间二甲苯汽化器 热油阀
        /// </summary>
        private OPCItem _valveOilRightItem;
        /// <summary>
        /// 间二甲苯进料调节阀
        /// </summary>
        private OPCItem _valveBenItem;
        /// <summary>
        /// 间二甲苯进料流量调节阀
        /// </summary>
        private OPCItem _valveBenTopItem;
        /// <summary>
        /// 空气加热器通往反应器阀门
        /// </summary>
        private OPCItem _valveO2ReactorItem;
        /// <summary>
        /// 热水泵进水阀
        /// </summary>
        private OPCItem _valveInHotPumpItem;
        /// <summary>
        /// 热水进入反应器阀门
        /// </summary>
        private OPCItem _valveH2ORecItem;
        /// <summary>
        /// 热油泵阀门
        /// </summary>
        private OPCItem _valveOilPumpItem;
        /// <summary>
        /// 闸阀1
        /// </summary>
        private OPCItem _valveGate1Item;

        //管道
        OPCItem FlowInCold_item;
        OPCItem FlowOutCold_item;
        OPCItem FlowOutHot_item;
        OPCItem FlowInSoftWater_item;
        OPCItem FlowOutOil_item;
        OPCItem FlowInBen_item;
        OPCItem FlowOutAmmoniaBen_item;
        OPCItem FlowInAmmonia_item;
        OPCItem FlowOutAmmonia_item;
        OPCItem FlowInO2_item;
        OPCItem FlowOutO2_item;
        OPCItem FlowOilInnerLoop_item;
        OPCItem FlowOilC8H10Ht_item;
        OPCItem FlowOutAirHt_item;
        OPCItem FlowO2Rec_item;
        OPCItem FlowOutElcHt_item;
        OPCItem FlowInElcHt_item;
        OPCItem FlowOutCold1_item;
        OPCItem FlowPumpOli_item;
        OPCItem FlowInBox_item;

        //标签
        OPCItem LabelFlowBenlene_item;
        OPCItem LabelFlowAmmonia_item;
        OPCItem LabelFlowO2_item;
        OPCItem LabelAmmoniaPressure_item;
        OPCItem LabelEletricTemperature_item;
        OPCItem LabelTemperature1_item;
        OPCItem LabelTemperature2_item;
        OPCItem LabelAmmoniaBenRateRate_item;
        OPCItem LabelGasBenRate_item;

        OPCItem LabelTempNH3_item;
        OPCItem LabelTempOil_item;


        //闪烁
        private OPCItem FlashAmmoniaFlow_item;
        private OPCItem FlashBenFlow_item;
        private OPCItem FlashAmmoniaPressure_item;
        private OPCItem FlashGasFlow_item;
        private OPCItem FlashAmmoniaBenRate_item;
        private OPCItem FlashGasBenRate_item;
        private OPCItem FlashTemperature1_item;
        private OPCItem FlashTemperature2_item;
        private OPCItem FlashEletricTemperature_item;
        private OPCItem FlashWarning_item;

        //可调节的阀门
        private OPCItem InputBen_item;
        private OPCItem InputAmmonia_item;
        #endregion

        #region 初始化
        public Amination(OPCServer opcserver, SerialPort port, bool isinner)
        {
            _opcServer = opcserver;
            _serialPort = port;
            Isinner = isinner;
            InitFiled();
            InitOPC();
            InitOPCItem();
            InitSignal();
        }

        private void InitFiled()
        {

            _flowBenzeneValue = 1; //间二甲苯流量
            _flowAmmoniaValue = 1;  //氨气流量
            _flowOxygenValue = 1;  //空气流量
            _pressureAmmoniaValue = 0.01;//氨气压力
            _tempratureElectricValue = DEFAULT_TEMPERATURE;  // 电加热器中温度
            _temperature1Value = DEFAULT_TEMPERATURE; //浓1处温度
            _temperature2Value = DEFAULT_TEMPERATURE;//浓2处温度
            _rateAmmoniaBenzeneValue = 1;//氨气与间二甲苯比例
            _rateGasBenzeneValue = 1;   //空气与间二甲苯比例

            _flow_oxygen_decrement = 5;
            _flow_benzene_decreament = 1;
            _flow_ammonia_decreament = 1;
        }

        private void InitSignal()
        {
            if (Isinner)
            {
                ListenSignal();
                _open = 1;
                _close = 0;

            }
            else
            {
                InitFlowCommandData();
                _serialPort.DataReceived += _serialPort_DataReceived;
                InitOpcItemWithSerialPort();
                ListenSerialPortAndAbnormalData();
                _open = 48;
                _close = 49;
            }
        }
        private void ListenSignal()
        {
            Task t = new Task(() =>
            {
                while (!_listenCts.IsCancellationRequested)
                {
                    var inAmmonia = Convert.ToInt32(ReadItem(FieldName.InAmmonia));
                    _valveInAmmoniaState = inAmmonia == _open;
                    var ammoniabuftank = Convert.ToInt32(ReadItem(FieldName.ValveNH3BufTank));
                    _valveAmmoniaBufTankState = ammoniabuftank == _open; 
                    var o2Airheater = Convert.ToInt32(ReadItem(FieldName.ValveO2AirHeater)) ;
                    _valveO2AirHeaterState = o2Airheater == _open;
                    var inEleheater = Convert.ToInt32(ReadItem(FieldName.ValveInEleHeater));
                    _valveInEleHeaterState = inEleheater == _open;
                    var valveOilLeft = Convert.ToInt32(ReadItem(FieldName.ValveOilLeft));
                    _valveOilLeftIState = valveOilLeft == _open;
                    var oliRight = Convert.ToInt32(ReadItem(FieldName.ValveOilRight));
                    _valveOilRightState = oliRight == _open;
                    var ben = Convert.ToInt32(ReadItem(FieldName.ValveBen));
                    _valveBenState = ben == _open;
                    var bentop = Convert.ToInt32(ReadItem(FieldName.ValveBenTop));
                    _valveBenTopState= bentop== _open;
                    var o2Reactor = Convert.ToInt32(ReadItem(FieldName.ValveO2Reactor));
                    _valveO2ReactorState = o2Reactor == _open;
                    var inhotPump = Convert.ToInt32(ReadItem(FieldName.ValveInHotPump));
                    _valveInHotPumpState = inhotPump == _open;
                    var h2orec = Convert.ToInt32(ReadItem(FieldName.ValveH2ORec));
                    _valveH2ORecState = h2orec == _open;
                    var oilpump = Convert.ToInt32(ReadItem(FieldName.ValveOilPump));
                    _valveOilPumpState = oilpump == _open;
                    var gate1 = Convert.ToInt32(ReadItem(FieldName.ValveGate1));
                    _valveGate1State = gate1 == _open;

                    DateTime dtnow = DateTime.Now;
                    Step step = new Step()
                    {
                        Date = dtnow,
                        Status =
                     { 
                         { StatusName.液氨进料调节阀, inAmmonia },
                         { StatusName.液氨到氨缓冲罐阀门, ammoniabuftank },
                          { StatusName.空气到加热器阀门, o2Airheater },
                          {StatusName.空气加热器到电加热器阀门,inEleheater},
                          {StatusName.氨气加热器热油阀_左侧, valveOilLeft},
                          {StatusName.苯汽化器热油阀_右侧,oliRight},
                          {StatusName.间二甲苯进料调节阀,ben},
                          {StatusName.苯流量调节阀,bentop},
                          {StatusName.空气加热器到反应器阀门,o2Reactor},
                          {StatusName.热水进料阀门,inhotPump},
                          {StatusName.热水进入反应器阀门,h2orec},
                          {StatusName.热油阀门,oilpump},
                          {StatusName.闸阀1,gate1},
                          {StatusName.间二甲苯流量,_flowBenzeneValue},
                          {StatusName.氨气流量,_flowAmmoniaValue},
                          {StatusName.空气流量,_flowOxygenValue},
                           {StatusName.氨缓冲罐压力,_pressureAmmoniaValue},
                           {StatusName.浓1温度,_temperature1Value},
                             {StatusName.氨气与间二甲苯比例,_rateAmmoniaBenzeneValue},
                         {StatusName.空气与间二甲苯比例,_rateGasBenzeneValue},
                     }
                    };
                    if (_isbeginned)
                        _steps.Add(step);
                    Thread.Sleep(500);
                    _isListenSingnalover = true;
                }
            });
            t.Start();

        }

        private void InitOPCItem()
        {
            //阀门
            _valveInAmmoniaItem = GetItem(FieldName.InAmmonia);
            _valveInAmmoniaItem.Close();
            _valveAmmoniaBufTankItem = GetItem(FieldName.ValveNH3BufTank);
            _valveAmmoniaBufTankItem.Close();
            _valveO2AirHeaterItem = GetItem(FieldName.ValveO2AirHeater);
            _valveO2AirHeaterItem.Close();
            _valveInEleHeaterItem = GetItem(FieldName.ValveInEleHeater);
            _valveInEleHeaterItem.Close();
            _valveOilLeftItem = GetItem(FieldName.ValveOilLeft);
            _valveOilLeftItem.Close();
            _valveOilRightItem = GetItem(FieldName.ValveOilRight);
            _valveOilRightItem.Close();
            _valveBenItem = GetItem(FieldName.ValveBen);
            _valveBenItem.Close();
            _valveBenTopItem = GetItem(FieldName.ValveBenTop);
            _valveBenTopItem.Close();
            _valveO2ReactorItem = GetItem(FieldName.ValveO2Reactor);
            _valveO2ReactorItem.Close();
            _valveInHotPumpItem = GetItem(FieldName.ValveInHotPump);
            _valveInHotPumpItem.Close();
            _valveH2ORecItem = GetItem(FieldName.ValveH2ORec);
            _valveH2ORecItem.Close();
            _valveOilPumpItem = GetItem(FieldName.ValveOilPump);
            _valveOilPumpItem.Close();
            _valveGate1Item = GetItem(FieldName.ValveGate1);
            _valveGate1Item .Close();

            //管道
            FlowInCold_item = GetItem(FieldName.FlowInCold); FlowInCold_item.Close();
            FlowOutCold_item = GetItem(FieldName.FlowOutCold); FlowOutCold_item.Close();
            FlowInSoftWater_item = GetItem(FieldName.FlowInSoftWater); FlowInSoftWater_item.Close();
            FlowOutOil_item = GetItem(FieldName.FlowOutOil); FlowOutOil_item.Close();
            FlowInBen_item = GetItem(FieldName.FlowInC8H10); FlowInBen_item.Close();
            FlowOutAmmoniaBen_item = GetItem(FieldName.FlowOutAmmoniaBen); FlowOutAmmoniaBen_item.Close();
            FlowInAmmonia_item = GetItem(FieldName.FlowInAmmonia); FlowInAmmonia_item.Close();
            FlowOutAmmonia_item = GetItem(FieldName.FlowOutAmmonia);
            FlowOutAirHt_item.Close();
            FlowInO2_item = GetItem(FieldName.FlowInO2); FlowInO2_item.Close();
            FlowOutO2_item = GetItem(FieldName.FlowOutO2); FlowOutO2_item.Close();
            FlowOilInnerLoop_item = GetItem(FieldName.FlowOilInnerLoop); FlowInO2_item.Close();
            FlowOilC8H10Ht_item = GetItem(FieldName.FlowOilC8H10Ht); FlowOilC8H10Ht_item.Close();
            FlowOutAirHt_item = GetItem(FieldName.FlowOutAirHt); FlowOutAirHt_item.Close();
            FlowO2Rec_item = GetItem(FieldName.FlowO2Rec); FlowO2Rec_item.Close();
            FlowOutElcHt_item = GetItem(FieldName.FlowOutElcHt); FlowOutElcHt_item.Close();
            FlowInElcHt_item = GetItem(FieldName.FlowInElcHt);
            FlowInElcHt_item.Close();
            FlowOutCold1_item = GetItem(FieldName.FlowOutCold1); FlowOutCold1_item.Close();
            FlowPumpOli_item = GetItem(FieldName.FlowPumpOil); FlowPumpOli_item.Close();
            FlowInBox_item = GetItem(FieldName.FlowInBox); FlowInBox_item.Close();
            //标签
            LabelFlowBenlene_item = GetItem(FieldName.LabelFlowBenlene); LabelFlowBenlene_item.Write(_flowBenzeneValue);
            LabelFlowAmmonia_item = GetItem(FieldName.LabelFlowNH3); LabelFlowAmmonia_item.Write(_flowAmmoniaValue);
            LabelFlowO2_item = GetItem(FieldName.LabelFlowO2); LabelFlowO2_item.Write(_flowOxygenValue);
            LabelAmmoniaPressure_item = GetItem(FieldName.LabelAmmoniaPressure);
            LabelAmmoniaPressure_item.Write(_pressureAmmoniaValue);

            LabelEletricTemperature_item = GetItem(FieldName.LabelEletricTemperature); LabelEletricTemperature_item.Write(_tempratureElectricValue);
            LabelTemperature1_item = GetItem(FieldName.LabelTemperature1); LabelTemperature1_item.Write(_temperature1Value);
            LabelTemperature2_item = GetItem(FieldName.LabelTemperature2); LabelTemperature2_item.Write(_temperature2Value);
            LabelTempNH3_item = GetItem(FieldName.LabelTempNH3); LabelTempNH3_item.Close();
            LabelAmmoniaBenRateRate_item = GetItem(FieldName.LabelAmmoniaBenRateRate);
            LabelAmmoniaBenRateRate_item.Write(_rateAmmoniaBenzeneValue);
            LabelGasBenRate_item = GetItem(FieldName.LabelGasBenRate); LabelGasBenRate_item.Write(_rateGasBenzeneValue);
            LabelTempOil_item = GetItem(FieldName.LabelTempOil); LabelTempOil_item.Close();

            //闪烁
            FlashAmmoniaFlow_item = GetItem(FieldName.FlashAmmoniaFlow);
            FlashAmmoniaBenRate_item.Close();
            FlashBenFlow_item = GetItem(FieldName.FlashBenFlow);
            FlashBenFlow_item.Close();
            FlashAmmoniaPressure_item = GetItem(FieldName.FlashAmmoniaPressure);
            FlashAmmoniaPressure_item.Close();
            FlashGasFlow_item = GetItem(FieldName.FlashGasFlow);
            FlashBenFlow_item.Close();
            FlashAmmoniaBenRate_item = GetItem(FieldName.FlashAmmoniaBenRate);
            FlashBenFlow_item.Close();
            FlashGasBenRate_item = GetItem(FieldName.FlashGasBenRate);
            FlashBenFlow_item.Close();
            FlashTemperature1_item = GetItem(FieldName.FlashTemperature1);
            FlashTemperature1_item.Close();
            FlashTemperature2_item = GetItem(FieldName.FlashTemperature2);
            FlashTemperature2_item.Close();
            FlashEletricTemperature_item = GetItem(FieldName.FlashEletricTemperature);
            FlashEletricTemperature_item.Close();
            FlashWarning_item = GetItem(FieldName.FlashWarning);
            FlashWarning_item.Close();


            //InputBen_item = GetItem(FieldName.InputBen);
            //InputBen_item.Write(0);
            //InputAmmonia_item = GetItem(FieldName.InputAmmonia);
            //InputAmmonia_item.Write(0);
        } 
        #endregion
        #region 外操初始化
        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

        }
        private void InitFlowCommandData()
        {

        }

        private void InitOpcItemWithSerialPort()
        {

        }

        private void ListenSerialPortAndAbnormalData()
        {

        }
        #endregion

        #region  重写公共方法
        bool _isbeginned = false;
        public override void Begin()
        {
            ListenOPCRelation();
            _isbeginned = true;
        }

        private bool _isListenSingnalover;
        public override async Task<string> CheckDefault()
        {  
            bool isOvertime = false;
            var loop = 0;
            StringBuilder builder = new StringBuilder();
            await Task.Run(() =>
            {
                if (!Isinner)
                {
                    Thread.Sleep(2000);
                    while (!_isgetoverstate1 || !_isgetoverstate2)
                    {
                        Thread.Sleep(1000);
                        loop++;
                        if (loop > 30)
                        {
                            isOvertime = true;
                            break;
                        }
                    }
                }
                else
                {
                    while (!_isListenSingnalover)
                    {
                        Thread.Sleep(_sleepfast);
                    }
                }
                if (_valveInAmmoniaState)
                    builder.AppendLine("液氨进料调节阀未关闭");
                if (_valveAmmoniaBufTankState)
                    builder.AppendLine("氨缓冲罐阀门未关闭");
                if (_valveO2AirHeaterState)
                    builder.AppendLine("空气阀未关闭");
                if (_valveInEleHeaterState)
                    builder.AppendLine("电加热器阀门未关闭");
                if (_valveOilLeftIState)
                    builder.AppendLine("氨气加热器阀门未关闭");
                if (_valveOilRightState)
                    builder.AppendLine("间二甲苯汽化器未关闭");
                if (_valveBenState)
                    builder.AppendLine("间二甲苯进料调节阀未关闭");
                if (_valveBenTopState)
                    builder.AppendLine("间二甲苯进料流量调节阀未关闭");
                if (_valveO2ReactorState)
                    builder.AppendLine("空气加热器连接反应器阀门未关闭");
                if (_valveInHotPumpState)
                    builder.AppendLine("热水泵进水阀未关闭");
                if (_valveH2ORecState)
                    builder.AppendLine("热水连接反应器阀门未关闭");
                if (_valveOilPumpState)
                    builder.AppendLine("热油泵阀门未关闭");
                if (_valveGate1State)
                    builder.AppendLine("闸阀1未关闭");
            });

            _details = GetDetailList(GetType().Name);
            if (_details == null)
                builder.AppendLine("可能由于网络原因，导致获取数据失败，请点击\"确定\"按钮 尝试重新获取");

            return builder.ToString();
        }

        public override void Over()
        {
            this._listenCts.Cancel();
            CalcFlow();
            //CalcFlowAndStep();
            Score = CalcScore();
            //CloseAllRelay();
            Finish();
        }

        //步骤 标识
        bool _isCanopenAmmonia = false;
        private void ListenOPCRelation()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {

                #region  闸阀正常开车前状态为开
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveGate1State)
                        {
                            if (Isinner) _valveGate1Item.Open();
                            FlowInBox_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner) _valveGate1Item.Close();
                            FlowInBox_item.StopFlow();
                        }
                    }
                });
                #endregion

                #region 风机系统

                #region  开启罗茨风机
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        //此处流量在300-600m3/h范围
                        if (_valveO2AirHeaterState)
                        {
                            if (!Isinner)
                                _valveO2AirHeaterItem.Open();
                            FlowInO2_item.StartFlow();
                            if (_flowOxygenValue < 300)
                            {
                                _flow_oxygen_increment = 10;
                            }
                            else if (_flowOxygenValue >= 600)
                            {
                                _flow_oxygen_increment =0;
                            }
                            else
                            {
                                _flow_oxygen_increment = 2;
                            }

                            if (_flowOxygenValue < 650)
                            {
                                _flowOxygenValue += _flow_oxygen_increment;
                                LabelFlowO2_item.Write(_flowOxygenValue);
                            }
                        }
                        else
                        {
                            if (!Isinner)
                            {
                                FlowInO2_item.Close();
                            }
                            FlowInO2_item.StopFlow();

                            _flowOxygenValue -= _flow_oxygen_decrement;
                            if (_flowOxygenValue <= 0)
                                _flowOxygenValue = 0;
                            LabelFlowO2_item.Write(_flowOxygenValue);
                        }

                        Thread.Sleep(_sleepfast);
                    }
                }
                    );
                #endregion

                #region 空气进去电加热器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInEleHeaterState)
                        {
                            if (!Isinner)
                                _valveInEleHeaterItem.Open();
                            //2段flow分开
                            FlowInElcHt_item.StartFlow();
                            FlowOutO2_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner)
                                _valveInEleHeaterItem.Close();
                            FlowInElcHt_item.StopFlow();
                            if (!_valveO2ReactorState)
                                FlowOutO2_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 空气直接进入流化床反应器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveO2ReactorState)
                        {
                            if (!Isinner)
                                _valveInEleHeaterItem.Open();
                            FlowO2Rec_item.StartFlow();
                            FlowOutO2_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner)
                                _valveInEleHeaterItem.Close();
                            FlowO2Rec_item.StopFlow();
                            if (!_valveInEleHeaterState)
                                FlowOutO2_item.StopFlow();
                        }
                    }
                });
                #endregion

                #region  电加热器进入流化床反应器 - 温度变化+

                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveO2AirHeaterState && _valveInEleHeaterState)
                        {
                            //空气进入规定温度
                            _temperature1_increment = _temperature1Value < 300 ? 3 : 1;
                            //开油泵 200度以上
                            if (_temperature1Value > 200)
                                _temperature1_increment = _valveOilPumpState ? 3 : 0;

                            if (_temperature1Value >= 360)
                            {
                                _temperature1_increment = 0;
                                _isCanopenAmmonia = true;
                            }
                            _temperature1Value += _temperature1_increment;
                            LabelTemperature1_item.Write(_temperature1Value);
                        }
                        else if (!_valveInEleHeaterState)
                        {
                            //降温 电加热器关闭
                            if (_temperature1Value > 350)
                            {
                                _temperature1Value -= 1;
                                LabelTemperature1_item.Write(_temperature1Value);
                            }
                        }

                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 吹空气，自然降温
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveO2AirHeaterState&&_valveO2ReactorState)
                        {
                            _temperature1_decrement = _temperature1Value < 60 ? 1 : 3;
                            _temperature1_decrement = _temperature1Value < 22 ? 0 : _temperature1_decrement;
                            _temperature1Value -= _temperature1_decrement;
                            LabelTemperature1_item.Write(_temperature1Value);
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion
                #endregion

                #region 氨气系统
                #region  液氨汽化 - 流量变化 -

                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInAmmoniaState)
                        {
                            if (!Isinner)
                                _valveInAmmoniaItem.Open();
                              FlowInAmmonia_item.Open();
                            _flowAmmoniaIncrement = _flowAmmoniaValue < 80 ? 3 : 0;
                            _flowAmmoniaValue += _flowAmmoniaIncrement;
                        }
                        else
                        {
                            FlowInAmmonia_item.Close();
                            _flowAmmoniaValue -= _flow_ammonia_decreament;
                            if (_flowAmmoniaValue < 0)
                                _flowAmmoniaValue = 0;
                        }
                        LabelFlowAmmonia_item.Write(_flowAmmoniaValue);
                        Thread.Sleep(_sleepfast);
                    }
                }
                    );


                #endregion

                #region  氨气进料 - 压力变化

                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInAmmoniaState && _valveAmmoniaBufTankState)
                        {
                            if (!Isinner) _valveAmmoniaBufTankItem.Open();
                            FlowOutAmmonia_item.StartFlow();
                            //规定压力[0.2-0.4]  //实际压力[0.1-0.5]
                            _pressure_ammonia_increment = _pressureAmmoniaValue <= 0.4 ? 0.005 : 0;
                            _pressureAmmoniaValue += _pressure_ammonia_increment;
                            LabelAmmoniaPressure_item.Write(_pressureAmmoniaValue);

                            var increament = _temperature1Value < 382 ? 2 : 0;

                            if (_temperature1Value > 200)
                                increament = _valveOilPumpState ? increament : 0;

                            _temperature1Value += increament;
                            LabelTemperature1_item.Write(_temperature1Value);

                        }
                        else
                        {
                            if (!Isinner)
                            {
                                _valveInAmmoniaItem.Close();
                                _valveAmmoniaBufTankItem.Close();
                            }
                            FlowOutAmmonia_item.Close();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #endregion

                #region  间二甲苯进料 - 流量变化
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveBenState)
                        {
                            if (!Isinner)
                                _valveBenItem.Open();
                            
                            if (_flowBenzeneValue < 60)
                                _flow_benzene_increament = 3;
                            else if (_flowBenzeneValue >= 110)
                                _flow_benzene_increament = 0;
                            else
                                _flow_benzene_increament = 2;

                            _flowBenzeneValue += _flow_benzene_increament;
                        }
                        else
                        {
                          
                            _flowBenzeneValue -= _flow_benzene_decreament;
                            if (_flowBenzeneValue < 0)
                                _flowBenzeneValue = 0;
                        }
                        LabelFlowBenlene_item.Write(_flowBenzeneValue);
                        Thread.Sleep(_sleepfast);
                    }
                });

                #endregion

                #region 间二甲苯 与 氨气 混合 放入流化床反应器 温度 | 由于设备上没有这个阀门，改成只要在这一步之前的阀门全开，就任务这个开了
                //苯相关的2个阀门打开
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInAmmoniaState && _valveAmmoniaBufTankState && _valveBenState && _valveBenTopState)
                        {
                            FlowInBen_item.StartFlow();
                            FlowOutAmmoniaBen_item.StartFlow();
                            //加二甲苯进料规定温度[380-430]  实际温度[380-460]
                            _temperature1_increment = _temperature1Value < 390 ? 2 : 0;
                            //开油泵 200度以上
                            if (_temperature1Value > 200)
                                _temperature1_increment = _valveOilPumpState ? _temperature1_increment : 0;

                             
                            _temperature1Value += _temperature1_increment;
                            LabelTemperature1_item.Write(_temperature1Value);



                            //计算比例
                            if (_flowBenzeneValue > 0)
                            {
                                var rate = _flowAmmoniaValue/(_flowBenzeneValue/9);
                                _rateAmmoniaBenzeneValue = Math.Round(rate, 2);
                                LabelAmmoniaBenRateRate_item.Write(_rateAmmoniaBenzeneValue);
                            }

                            if (_flowBenzeneValue > 0)
                            {
                                var rate = _flowOxygenValue/(_flowBenzeneValue/7);
                                _rateGasBenzeneValue = Math.Round(rate, 2);
                                LabelGasBenRate_item.Write(_rateGasBenzeneValue);
                            }


                        }
                        else
                        {
                            if (!Isinner)
                                FlowOutAmmoniaBen_item.Close();
                            FlowInBen_item.StopFlow();
                            FlowOutAmmoniaBen_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });



                #endregion

                #region 热水
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInHotPumpState &&!Isinner)
                        {
                            _valveInHotPumpItem.Open();
                        }
                        if (_valveH2ORecState && !Isinner)
                        {
                            _valveH2ORecItem.Open();
                        }

                        if (_valveInHotPumpState && _valveH2ORecState)
                        {
                            FlowInSoftWater_item.StartFlow();
                            if (_temperature1Value >= 380 && _temperature1Value <= 425)
                            {
                                _temperature1Value += 2;
                                LabelTemperature1_item.Write(_temperature1Value);
                            }
                        }
                        else
                        {
                            FlowInSoftWater_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion


            });
        }

        private void CalcFlow()
        {
            //1.开车步骤
            //1.1打开风机
            var avgFlowO2Count = _steps.Count(i => i.Status[StatusName.空气流量] >= 300 && i.Status[StatusName.空气流量] <= 600);
            var avgFlowO2CountInvert = _steps.Count(i => i.Status[StatusName.空气流量] < 300 || i.Status[StatusName.空气流量] > 600);

            //1.2外循环打开的item
            var firstLoopOpen = _steps.FirstOrDefault(i => i.Status[StatusName.热油阀门] == _open);

            //1.2氨气流量
            
            var firstOpenAmmonia = _steps.FirstOrDefault(i => i.Status[StatusName.液氨进料调节阀] == _open);
            var avgFlowAmmoniaCount =
                _steps.Count(i => i.Status[StatusName.氨气流量] >= 20 && i.Status[StatusName.氨气流量] <= 80);
            var avgFlowAmmoniaCountInvert =
               _steps.Count(i => i.Status[StatusName.氨气流量] < 20 && i.Status[StatusName.氨气流量] > 80);
            
            //1.3氨气压力
            var pressureAmmonia =
                _steps.Count(i => i.Status[StatusName.氨缓冲罐压力] >= 0.2 && i.Status[StatusName.氨缓冲罐压力] <= 0.45);

            //1.4 间二甲苯流量
            var firstOpenBen = _steps.FirstOrDefault(i => i.Status[StatusName.间二甲苯进料调节阀] == _open);
            var avgFlowBen = _steps.Count(i => i.Status[StatusName.间二甲苯流量] >= 60 && i.Status[StatusName.间二甲苯流量] < 120);

            //1.5计算比例
            var rate1 = _steps.Where(i => i.Status[StatusName.间二甲苯进料调节阀] > 0 && i.Status[StatusName.苯流量调节阀] == _open && i.Status[StatusName.液氨进料调节阀] == _open &&
                i.Status[StatusName.液氨到氨缓冲罐阀门] == _open).Count(i => i.Status[StatusName.氨气与间二甲苯比例]>=5&&i.Status[StatusName.氨气与间二甲苯比例]<=7) ;

            var rate2 =
                _steps.Where(
                    i =>
                        i.Status[StatusName.空气到加热器阀门] == _open && i.Status[StatusName.间二甲苯进料调节阀] == _open &&
                        i.Status[StatusName.苯流量调节阀] == _open)
                    .Count(i => i.Status[StatusName.空气与间二甲苯比例] >= 35 && i.Status[StatusName.空气与间二甲苯比例] <= 40);

            //1.6反应温度、时间
            var avgTemperatureCount = _steps.Count(i => i.Status[StatusName.浓1温度] >= 390&&i.Status[StatusName.浓1温度]<=430);

           


            //计算分数
            int reactionCount = 60;
            #region 开车步骤
            //1打开风机
            if (avgFlowO2Count != 0)
            {
                if (avgFlowO2Count > reactionCount)
                {
                    AddCompose("开启风机：空气流量在正常范围300-600 m3/h");
                }
                else if (avgFlowO2CountInvert > avgFlowO2Count)
                {
                    AddCompose("开启风机：空气流量不在正常范围300-600 m3/h");
                }
            }
            else
            {
                AddCompose("开启风机：控制空气流量，未操作");
            }

            //2开启外循环泵 导热油
            if (firstLoopOpen != null)
            {
                var temperature_loop = firstLoopOpen.Status[StatusName.浓1温度];
                if (temperature_loop >= 170 && temperature_loop <= 220)
                    AddCompose("打开导热油循环泵：反应器温度在正常范围170-220℃");
                else if (temperature_loop < 170)
                    AddCompose("开导热油循环泵：反应器温度低于170℃");
                else
                    AddCompose("开导热油循环泵：反应器温度高于220℃");
            }
            else
            {
                AddCompose("开导热油循环泵：未操作");

            }
           

            //3通入氨气
            //3.1 氨气阀门打开时间
            if (firstOpenAmmonia != null)
            {
                var temperature_ammonia = firstOpenAmmonia.Status[StatusName.浓1温度];
                if (_isCanopenAmmonia)
                {
                    if (temperature_ammonia <= 350)
                        AddCompose("锥底温度降至350℃，打开氨气阀");
                    else
                        AddCompose("锥底温度高于350℃，打开氨气阀");
                }
                else
                {
                    AddCompose("锥底温度未到达360℃，过早打开氨气阀");
                }
            }
            else
            {
                AddCompose("打开氨气阀，未操作");
            }

            //3.2 氨气流量
            if (avgFlowAmmoniaCount != 0)
            {
                if (avgFlowAmmoniaCount > reactionCount)
                {
                    AddCompose("氨气进料：流量在正常范围20-80m3/h");
                }
                else if (avgFlowAmmoniaCountInvert > avgFlowAmmoniaCount)
                {
                    AddCompose("氨气进料：流量不在正常范围20-80m3/h");
                }
            }
            else
            {
                AddCompose("氨气进料：流量控制，未操作");
            }

            //3.3 氨气缓冲罐的压力 
            if (pressureAmmonia != 0)
            {
                if (pressureAmmonia > reactionCount)
                {
                    AddCompose("氨气缓冲罐压力：压力在正常范围0.2-0.4Mpa");
                }
                else
                {
                    AddCompose("氨气缓冲罐压力：压力不在正常范围0.2-0.4Mpa");
                }                
            }
            else
            {
                AddCompose("氨气缓冲罐压力：压力控制未操作");
            }
            #endregion

            #region 4.通入间二甲苯
            //4.1打开间二甲苯进料阀
            if (firstOpenBen != null)
            {
                var temperature_ben = firstOpenBen.Status[StatusName.浓1温度];
                if (temperature_ben >= 380)
                    AddCompose("锥底温度达380℃，打开间二甲苯进料阀");
                else
                    AddCompose("锥底温度未达380℃，打开间二甲苯进料阀");
            }
            else
            {
                AddCompose("打开间二甲苯进料阀，未操作");
            }
            //4.2间二甲苯进料时，流量的检测
            if (avgFlowBen != 0)
            {
                if (avgFlowBen >= reactionCount)
                {
                    AddCompose("间二甲苯进料：流量在正常范围60-120L/h");
                }
                else
                {
                    AddCompose("间二甲苯进料：流量不在正常范围60-120L/h");
                }
            }
            else
            {
                AddCompose("间二甲苯进料：流量控制，未操作");
            }

            //4.3氨气与间二甲苯混合气体进入，氨气与间二甲苯比例
            if (rate1 != 0)
            {
                if (rate1 >=reactionCount)
                    AddCompose("氨气与间二甲苯比例在正常范围5-7 mol%");
                else
                    AddCompose("氨气与间二甲苯比例不在正常范围5-7 mol%");
            }

            //4.4空气与间二甲苯比例
            if (rate2 != 0)
            {
                if (rate2 >=reactionCount)
                    AddCompose("空气与间二甲苯比例在正常范围35-40 v%");
                else
                    AddCompose("空气与间二甲苯比例不在正常范围35-40 v%");
            }
            #endregion

            bool  isreactionover = false;
            #region 5.反应温度[390-425] 和 反应时间
            if (avgTemperatureCount!=0)
            {
                if(avgTemperatureCount>=reactionCount)
                    AddCompose("反应温度：浓1处温度在正常范围390-425℃");
                else
                    AddCompose("反应温度：浓1处温度不在正常范围390-425℃");
                
                if (avgTemperatureCount > reactionCount)
                {
                    AddCompose("反应时间正常");
                    isreactionover = true;
                }
                else
                {
                    AddCompose("反正时间不足");
                }
            }
            #endregion


            #region 6.停车


            //停车
            #region 停车计算
            //2.1 关闭间二甲苯进料相关阀门
            var benlene_latestopen_item = _steps.Where(i => i.Status[StatusName.间二甲苯进料调节阀] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
            var benleneCloseItem = benlene_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.间二甲苯进料调节阀] == _close && i.Date >
                benlene_latestopen_item.Date && isreactionover).OrderBy(i => i.Date).FirstOrDefault() : null;

            // 2.2  关闭氨气进料阀门
            var nitrogen_latestopen_item = _steps.Where(i => i.Status[StatusName.液氨进料调节阀] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
            var ammoniaCloseItem = nitrogen_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.液氨进料调节阀] == _close && i.Date >
                nitrogen_latestopen_item.Date && isreactionover).OrderBy(i => i.Date).FirstOrDefault() : null;

            //2.3关闭热油、热水系统
            var hotOilOpenItem =
                _steps.Where(i => i.Status[StatusName.热油阀门] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
            var hotOilCloseItem = hotOilOpenItem != null
                ? _steps.Where(i => i.Status[StatusName.热油阀门] == _close && i.Date > hotOilOpenItem.Date &&isreactionover)
                    .OrderBy(i => i.Date)
                    .FirstOrDefault()
                : null;

            var hotWaterCloseItem =
                _steps.Where(i => i.Status[StatusName.热水进料阀门] == _close && i.Status[StatusName.热水进入反应器阀门] == _close && isreactionover)
                    .OrderBy(i => i.Date)
                    .FirstOrDefault();



            //2.3空气直接到反应器阀门
            var o2react_latestopen_item = _steps.Where(i => i.Status[StatusName.空气加热器到反应器阀门] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
            var o2react_close_item = o2react_latestopen_item != null
                ? _steps.Where(i => i.Status[StatusName.空气加热器到反应器阀门] == _close && i.Date > o2react_latestopen_item.Date)
                    .OrderBy(i => i.Date)
                    .FirstOrDefault()
                : null;
            var temp2_item = o2react_close_item != null
                ? _steps.Where(i => i.Status[StatusName.空气加热器到反应器阀门] == _open && i.Date > o2react_close_item.Date
                    ).OrderByDescending(i => i.Status[StatusName.浓1温度]).ThenByDescending(i => i.Date).FirstOrDefault()
                : null;

            // 2.4 关闭空气阀门
            var O2_latestopen_item = _steps.Where(i => i.Status[StatusName.空气到加热器阀门] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
            var O2_close_item = O2_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.空气到加热器阀门] == _close
                && i.Date > O2_latestopen_item.Date && isreactionover).OrderBy(i => i.Date).FirstOrDefault() : null; 
            #endregion

            //6.1 停止通间二甲苯 , 停止通氨

            if (benleneCloseItem != null && ammoniaCloseItem != null)
            {
                if (benleneCloseItem.Date < ammoniaCloseItem.Date)
                {
                    AddCompose("停车：关闭间二甲苯进料阀门");
                    AddCompose("停车：关闭氨气阀门");
                }
                else
                {
                    AddCompose("停车：关闭氨气阀门、关闭间二甲苯阀门顺序错误");
                }
            }
            else
            {
                AddCompose("停车：关闭间二甲苯调节阀、氨气进料调节阀未操作或反应未完成提前关闭");
            }

            if (hotOilCloseItem != null)
            {
                AddCompose("停车：关闭热油阀门");
            }
            else
            {
                AddCompose("停车：关闭热油阀门未操作或提前关闭");
            }
            if (hotWaterCloseItem != null)
            {
                AddCompose("停车：关闭热水进水阀阀门");
            }
            else
            {
                AddCompose("停车：关闭热水进水阀阀门未操作或提前关闭");
            }

            #endregion

            #region 7.降温

            if (temp2_item != null)
            {
                var temp2 = temp2_item.Status[StatusName.浓1温度];
                if (temp2 < 60)
                {
                    AddCompose("空气吹扫：锥底降到正常温度60以下");
                }
                else
                {
                    AddCompose("空气吹扫：锥底未降到正常温度60℃以下");
                }
            }
            else
            {
                AddCompose("空气吹扫：锥底降温，未操作");
            }



            if (ammoniaCloseItem != null && O2_close_item != null)
            {
                if (ammoniaCloseItem.Date < O2_close_item.Date)
                {
                    AddCompose("停车：空气阀门关闭");
                }
                else
                {
                    AddCompose("停车：关闭空气阀门、氨气进料阀顺序错误");
                }
            }
            else
            {
                AddCompose("停车：关闭空气进料阀门未操作或提前关闭");
            }
            #endregion
        }

        private void CalcFlowAndStep()
        {
            #region 计算流程
            //1.正常开车步骤

            //1.1 计算空气流量

            var avg_flowO2_count = _steps.Count(i => i.Status[StatusName.空气到加热器阀门] == _open);
            var avg_flowO2 = avg_flowO2_count > 0 ? _steps.Where(i => i.Status[StatusName.空气到加热器阀门] == _open).Average(i => i.Status[StatusName.空气流量]) : -1;

            //外循环打开的item
            var first_loopopen_item = _steps.FirstOrDefault(i => i.Status[StatusName.热油阀门] == _open);

            //1.2 氨气流量
            var avg_flowammonia_count = _steps.Count(i => i.Status[StatusName.液氨进料调节阀] == _open && i.Status[StatusName.液氨到氨缓冲罐阀门] == _open);
            var avg_flowammonia = avg_flowammonia_count > 0 ?
                _steps.Where(i => i.Status[StatusName.液氨进料调节阀] > 0 && i.Status[StatusName.液氨到氨缓冲罐阀门] == _open).Average(i => i.Status[StatusName.氨气流量]) : -1;
            //1.2.1首次打开氨气阀门的item
            var first_ammoniaopen_item = _steps.FirstOrDefault(i => i.Status[StatusName.液氨进料调节阀] == _open);

            //1.3 氨气压力
            var nitrogenpressure_count = _steps.Count(i => i.Status[StatusName.液氨进料调节阀] ==_open && i.Status[StatusName.液氨到氨缓冲罐阀门] == _open);
            var nitrogenpressure = nitrogenpressure_count > 0 ? _steps.Where(i => i.Status[StatusName.液氨进料调节阀] > 0 && i.Status[StatusName.液氨到氨缓冲罐阀门] == _open).Average(i => i.Status[StatusName.氨缓冲罐压力]) : -1;

            //1.4 间二甲苯流量
            var first_benopen_item = _steps.FirstOrDefault(i => i.Status[StatusName.间二甲苯进料调节阀] ==_open);
            var flowxylene_count = _steps.Count(i => i.Status[StatusName.间二甲苯进料调节阀] ==_open);
            var flowxylene = flowxylene_count > 0 ? _steps.Where(i => i.Status[StatusName.间二甲苯进料调节阀] ==_open).Average(i => i.Status[StatusName.间二甲苯流量]) : -1;
            //1.5 氨气：苯          开4个
            var rate1_count = _steps.Count(i => i.Status[StatusName.间二甲苯进料调节阀] > 0 && i.Status[StatusName.苯流量调节阀] == _open && i.Status[StatusName.液氨进料调节阀]==_open &&
                i.Status[StatusName.液氨到氨缓冲罐阀门] == _open);
            var rate1 = rate1_count > 0 ? _steps.Where(i => i.Status[StatusName.间二甲苯进料调节阀] > 0 && i.Status[StatusName.苯流量调节阀] == _open && i.Status[StatusName.液氨进料调节阀] == _open &&
                i.Status[StatusName.液氨到氨缓冲罐阀门] == _open).Average(i => i.Status[StatusName.氨气与间二甲苯比例]) : -1;

            //1.6 空气与苯比例
            //var rate2_count = _steps.Count(i=>i.Status[StatusName.空气阀门]==open &&i.Status[StatusName.空气流入电加热器阀门]==open &&i.Status[StatusName.空气流出电加热器]==open
            //    && i.Status[StatusName.间二甲苯进料阀]==open&& i.Status[StatusName.间二甲苯流入反应器阀门]==open);
            //var rate2 = rate2_count > 0 ? _steps.Where(i => i.Status[StatusName.空气阀门] == open && i.Status[StatusName.空气流入电加热器阀门] == open && i.Status[StatusName.空气流出电加热器] == open
            //    && i.Status[StatusName.间二甲苯进料阀] == open && i.Status[StatusName.间二甲苯流入反应器阀门] == open).Average(i => i.Status[StatusName.空气与间二甲苯比例]) : -1;
            var rate2_count = _steps.Count(i => i.Status[StatusName.空气到加热器阀门] == _open && i.Status[StatusName.间二甲苯进料调节阀] ==_open && i.Status[StatusName.苯流量调节阀] == _open);
            var rate2 = rate2_count > 0 ? _steps.Where(i => i.Status[StatusName.空气到加热器阀门] == _open && i.Status[StatusName.间二甲苯进料调节阀] == _open && i.Status[StatusName.苯流量调节阀] == _open).Average(i => i.Status[StatusName.空气与间二甲苯比例]) : -1;

            //1.7 软水进，浓1处降温
            //todo:待处理 2016-8-17

            //var temp1_count = _steps.Count(i => i.Status[StatusName.冷却水进水阀] == open);
            //var temp1 = temp1_count > 0 ? _steps.Where(i => i.Status[StatusName.冷却水进水阀] == open).Average(i => i.Status[StatusName.浓1温度]) : -1;

            //1.8平均温度,  计算>390
            var avg_temperature_items = _steps.Where(i => i.Status[StatusName.浓1温度] > 390);


            //2停车步骤：
            //2.1 关闭间二甲苯进料相关阀门
            var benlene_latestopen_item = _steps.Where(i => i.Status[StatusName.间二甲苯进料调节阀] ==_open).OrderByDescending(i => i.Date).FirstOrDefault();
            var benlene_close_item = benlene_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.间二甲苯进料调节阀] == _close && i.Date >
                benlene_latestopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;
            // 2.2  关闭氨气进料阀门
            var nitrogen_latestopen_item = _steps.Where(i => i.Status[StatusName.液氨进料调节阀] ==_open).OrderByDescending(i => i.Date).FirstOrDefault();
            var ammonia_close_item = nitrogen_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.液氨进料调节阀] == _close && i.Date >
                nitrogen_latestopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;
            //2.3 关闭混合阀门
            //todo:有没有这个阀门呢？

            //var ammoniaben_lastopen_item = _steps.Where(i => i.Status[StatusName.间二甲苯流入反应器阀门] == open).OrderByDescending(i => i.Date).FirstOrDefault();
            //var ammoniaben_close_item = ammoniaben_lastopen_item != null ? _steps.Where(i => i.Status[StatusName.间二甲苯流入反应器阀门] == close && i.Date > ammoniaben_lastopen_item.Date)
            //    .OrderBy(i => i.Date).FirstOrDefault() : null;


            //var mixed_lateestopen_item = _steps.Where(i => i.Status[StatusName.间二甲苯流入反应器阀门] == open).OrderByDescending(i => i.Date).FirstOrDefault();
            //var mixed_close_item = mixed_lateestopen_item != null ? _steps.Where(i => i.Status[StatusName.间二甲苯流入反应器阀门] == close).OrderBy(i => i.Date).FirstOrDefault() : null;


            //var softwater_latesteopen_item = _steps.Where(i => i.Status[StatusName.经热水泵进水阀门] == open).OrderByDescending(i => i.Date).FirstOrDefault();
            //var softwater_close_item = softwater_latesteopen_item != null ? _steps.Where(i => i.Status[StatusName.经热水泵进水阀门] == close &&
            //    i.Date > softwater_latesteopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;

            // 2.3 降温到60C以下
           var o2react_latestopen_item = _steps.Where(i => i.Status[StatusName.空气到加热器阀门] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
           var o2react_close_item = o2react_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.空气到加热器阀门] == _close && i.Date > o2react_latestopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;
            var temp2_item = o2react_close_item != null ? _steps.Where(i => i.Status[StatusName.空气到加热器阀门] == _open && i.Date > o2react_close_item.Date
                ).OrderByDescending(i => i.Status[StatusName.浓1温度]).ThenByDescending(i => i.Date).FirstOrDefault() : null;

            // 2.4 关闭空气阀门
            var O2_latestopen_item = _steps.Where(i => i.Status[StatusName.空气到加热器阀门] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
            var O2_close_item = O2_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.空气到加热器阀门] == _close
                && i.Date > O2_latestopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;


            #endregion

            #region  计算分数
            #region 1.开启罗茨风机，空气流量

            if (avg_flowO2 != -1)
            {
                if (avg_flowO2 < 300)
                {
                    AddCompose("开启风机：空气流量小于300 m3/h");
                }
                else if (avg_flowO2 >= 300 && avg_flowO2 <= 600)
                {
                    AddCompose("开启风机：空气流量在正常范围300-600 m3/h");
                }
                else
                {
                    AddCompose("开启风机：空气流量值超过600 m3/h");
                }
            }
            else
            {
                AddCompose("开启风机：控制空气流量未操作");
            }
            #endregion

            #region 2.开外循环泵

            if (first_loopopen_item != null)
            {
                var temperature_loop = first_loopopen_item.Status[StatusName.浓1温度];
                if (temperature_loop >= 170 && temperature_loop <= 220)
                    AddCompose("打开导热油循环泵");
                else if (temperature_loop < 170)
                    AddCompose("打开导热油循环泵过早");
                else
                    AddCompose("打开导热油循环泵过晚");
            }
            else
            {
                AddCompose("打开导热油循环泵，未操作");
            }
            #endregion

            #region 3.通入氨气
            //3.1 氨气阀门打开时间
            if (first_ammoniaopen_item != null)
            {
                var temperature_ammonia = first_ammoniaopen_item.Status[StatusName.浓1温度];
                if (_isCanopenAmmonia)
                {
                    if (temperature_ammonia <= 350)
                        AddCompose("锥底温度降至350℃，打开氨气阀");
                    else
                        AddCompose("锥底温度高于350℃，打开氨气阀");
                }
                else
                {
                    AddCompose("锥底温度未到达360℃，过早打开氨气阀");
                }
            }
            else
            {
                AddCompose("打开氨气阀，未操作");
            }

            //3.2 氨气流量
            if (avg_flowammonia != -1)
            {
                if (avg_flowammonia < 20)
                {
                    AddCompose("氨气进料：流量值小于20 m3/h");
                }
                else if (avg_flowammonia >= 20 && avg_flowammonia <= 80)
                {
                    AddCompose("氨气进料：流量在正常范围20-80m3/h");
                }
                else
                {
                    AddCompose("氨气进料：流量值超过80m3/h");
                }
            }
            else
            {
                AddCompose("氨气进料：流量控制，未操作");
            }

            //3.3 氨气缓冲罐的压力 
            if (nitrogenpressure != -1)
            {
                if (nitrogenpressure < 0.2)
                {
                    AddCompose("氨气缓冲罐压力：压力低压0.2MPa");
                }
                else if (nitrogenpressure >= 0.2 && nitrogenpressure <= 0.4)
                {
                    AddCompose("氨气缓冲罐压力：压力在正常范围0.2-0.4Mpa");
                }
                else
                {
                    AddCompose("氨气缓冲罐压力：压力高于0.4MPa");
                }
            }
            else
            {
                AddCompose("氨气缓冲罐压力：压力控制未操作");
            }
            #endregion

            #region 4.通入间二甲苯
            //4.1打开间二甲苯进料阀
            if (first_benopen_item != null)
            {
                var temperature_ben = first_benopen_item.Status[StatusName.浓1温度];
                if (temperature_ben >= 380)
                    AddCompose("锥底温度达380℃，打开间二甲苯进料阀");
                else
                    AddCompose("锥底温度未达380℃，打开间二甲苯进料阀");
            }
            else
            {
                AddCompose("锥底温度未达380℃，打开间二甲苯进料阀，未操作");
            }
            //4.2间二甲苯进料时，流量的检测
            if (flowxylene != -1)
            {
                if (flowxylene < 60)
                    AddCompose("间二甲苯进料：流量小于60L/h");
                else if (flowxylene >= 60 && flowxylene <= 120)
                    AddCompose("间二甲苯进料：流量在正常范围60-120L/h");
                else
                    AddCompose("间二甲苯进料：流量大于120L/h");
            }
            else
            {
                AddCompose("间二甲苯进料：流量控制，未操作");
            }

            //4.3氨气与间二甲苯混合气体进入，氨气与间二甲苯比例
            if (rate1 != -1)
            {
                if (rate1 < 5)
                    AddCompose("氨气与间二甲苯比例小于5 mol%");
                else if (rate1 >= 5 && rate1 <= 7)
                    AddCompose("氨气与间二甲苯比例正常范围5-7 mol%");
                else
                    AddCompose("氨气与间二甲苯比例大于7 mol%");
            }

            //4.4空气与间二甲苯比例
            if (rate2 != -1)
            {
                if (rate2 < 35)
                    AddCompose("空气与间二甲苯比例小于35 v%");
                else if (rate2 >= 35 && rate2 <= 40)
                    AddCompose("空气与间二甲苯比例在正常范围35-40 v%");
                else
                    AddCompose("空气与间二甲苯比例大于40 v%");
            }
            #endregion
            bool isreactionover = false;

            #region 5.反应温度[390-425] 和 反应时间
            if (avg_temperature_items.Any())
            {
                var avg_temperature = avg_temperature_items.Average(i => i.Status[StatusName.浓1温度]);
                if (avg_temperature >= 390 && avg_temperature <= 425)
                {
                    AddCompose("反应温度：浓1处温度在正常范围390-425℃");
                }
                else if (avg_temperature < 390)
                {
                    AddCompose("反应温度：浓1处温度低于390℃");
                }
                else
                {
                    AddCompose("反应温度：浓1处温度高于425℃");
                }


                var avg_temperature_count = avg_temperature_items.Count();
                var reaction_total_second = avg_temperature_count / 2;
                if (reaction_total_second > _reactionSecond)
                {
                    AddCompose("反应时间正常");
                    isreactionover = true;
                }
                else
                {
                    AddCompose("反正时间不足");
                }
            }
            #endregion




            #region 6.停车
            //6.1 停止通间二甲苯 ， 停止通氨，混合阀门
            if (benlene_close_item != null && ammonia_close_item != null)
            {
                if (isreactionover)
                {
                    if (benlene_close_item.Date < ammonia_close_item.Date)
                    {
                        AddCompose("停车：关闭间二甲苯进料阀门");
                        AddCompose("停车：关闭氨气阀门");
                    }
                    else
                    {
                        AddCompose("停车：关闭氨气阀门早于关闭间二甲苯阀门");
                    }
                    //todo:待处理
                    //if (ammoniaben_close_item != null)
                    //{
                    //    if (ammoniaben_close_item.Date > benlene_close_item.Date)
                    //        AddCompose("停车：关闭混合器阀门");
                    //    else
                    //        AddCompose("停车：关闭混合器阀门早于关闭间二甲苯阀门");
                    //}
                }
                else
                {
                    AddCompose("停车：反应未完成，过早关闭间二甲苯阀门和氨气阀门");
                }
            }
            else
            {
                AddCompose("停车：关闭间二甲苯调节阀、氨气进料调节阀未操作");
            }
            #endregion

            #region 7.降温

            if (temp2_item != null)
            {
                var temp2 = temp2_item.Status[StatusName.浓1温度];
                if (temp2 < 60)
                {
                    AddCompose("锥底降到正常温度60℃下");
                }
            }
            else
            {
                AddCompose("锥底降温：未操作");
            }
            if (ammonia_close_item != null && O2_close_item != null)
            {
                if (ammonia_close_item.Date < O2_close_item.Date)
                {
                    AddCompose("停车：空气进料阀门关闭");
                }
            }
            else
            {
                AddCompose("停车：关闭空气进料阀门未操作");
            }
            #endregion
            #endregion
        }
        #endregion


        #region 枚举定义
        enum FieldName
        {
            //开关


            //管道
            FlowInCold, FlowOutCold, FlowInSoftWater, FlowOutOil, FlowInC8H10, FlowOutAmmoniaBen, FlowInO2, FlowOilInnerLoop, FlowOilNH3Ht,
            FlowOilC8H10Ht, FlowOutAirHt, FlowO2Rec, FlowOutO2, FlowOutElcHt, FlowOutCold1, FlowPumpOil, FlowInBox,

            //标签
            LabelFlowNH3, LabelFlowO2, LabelTemperature1, LabelTemperature2, LabelTempNH3,
            LabelTempOil,
            //闪烁
            FlashTemperature1, FlashTemperature2,
            FlashAmmoniaFlow,
            FlashBenFlow,
            FlashGasFlow,
            FlashAmmoniaBenRate,
            FlashGasBenRate,
            FlashEletricTemperature,
            FlashAmmoniaPressure,

            LabelAmmoniaBenRateRate,
            LabelFlowBenlene,
            LabelAmmoniaPressure,
            LabelEletricTemperature,
            LabelGasBenRate,
            FlowOutAmmonia,
            FlowInAmmonia,
            FlowInElcHt,
            FlashWarning,
            InAmmonia,
            ValveBen,
            ValveBenTop,
            ValveNH3BufTank,
            ValveO2AirHeater,
            ValveInEleHeater,
            ValveOilLeft,
            ValveOilRight,
            ValveO2Reactor,
            ValveInHotPump,
            ValveH2ORec,
            ValveOilPump,
            ValveGate1
        }
        enum StatusName
        {
            液氨进料调节阀,
            液氨到氨缓冲罐阀门,
            空气到加热器阀门,
            空气加热器到电加热器阀门,
            氨气加热器热油阀_左侧,
            苯汽化器热油阀_右侧,
            间二甲苯进料调节阀,
            苯流量调节阀,
            空气加热器到反应器阀门,
            热水进料阀门,
            热水进入反应器阀门,
            热油阀门,
            闸阀1,
            间二甲苯流量,
            空气流量,
            氨气流量,
            氨缓冲罐压力,
            浓1温度,
            氨气与间二甲苯比例,
            空气与间二甲苯比例

        }

        private enum WarningType
        {
            温度异常,
            泄漏
        }

        #endregion
    }
}
